import numpy as np
from FaceAPI import FaceApi
from BosAPI import BosApi
import json
import time
import cv2
import RPi.GPIO as GPIO
import wxpy
import datetime
import time

config = None
fristFrame = None
cnts = None

GPIO.setmode(GPIO.BOARD)

with open('./configs/config.json', 'r') as f:
    config = json.load(f)

face = FaceApi(config['faceappid'], config['faceapikey'], config['facesecretkey'], configdict={
    "therhold": int(config['therhold']),
    "facegroup": str(config['group'])
})

obs = BosApi(config['bosapikey'], config['boscretkey'], config_dict={
    "endpoint": str(config['bosendpoint']),
    "bucketname": str(config['bosbucketname'])
})

bot = wxpy.Bot()
bot.self.add()
friends = bot.friends().search(config['wxname'])

video = cv2.VideoCapture(0)

GPIO_IN = 12
GPIO.setup(GPIO_IN, GPIO.IN)

def push(img, message, noise):
    global obs, bot
    print(obs(img, './tmps/{}.jpg'.format(noise)))
    print('[INFO] Runner ...')
    bot.self.send_image(img)
    friends.send_image(img)
    print('[INFO] Send Messages!')
result = None
while True:
    seed = str(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
    (_, frame) = video.read()
    cv2.imwrite('./{}/{}.jpg'.format(config['savepath'], seed), frame)
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    gray = cv2.GaussianBlur(gray, (21, 21), 0)
    if fristFrame == None:
        fristFrame = gray
        continue
    frameDelta = cv2.absdiff(fristFrame, gray)
    thresh = cv2.threshold(frameDelta, 25, 255, cv2.THRESH_BINARY)[1]
    thresh = cv2.dilate(thresh, None, iterations=2)
    (cnts, _) = cv2.findContours(thresh.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
    cv2.imshow('thresh', thresh)
    for c in cnts:
        if cv2.contourArea(c) < 10000:
            continue
        (x, y, w, h) = cv2.boundingRect(c)
        t = frame[x:x+w, y:y+h]
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
        cv2.imwrite('./runnertmp/s.jpg', t)
        try:
            result = face('./runnertmp/s.jpg')
        except:
	    pass
	try:
	    if result[0] == True:
                print('[INFO] It\'s people in the facesets!')
            else:
            	print('[ERROR] The Home coming!')
            	push(img='./{}/{}.jpg'.format(config['savepath'], seed), message='[ERROR] The home coming!', noise=seed)
    	except:
	    pass
    cv2.imshow('Frame', frame)
    cv2.waitKey(1)
